package com.jeecg;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Processor extends Thread{
	private Socket socket;
	private InputStream in;
	private PrintStream out;
	//获取项目根目录
	public final static String WEB_ROOT=System.getProperty("user.dir"); 
	
	public Processor(){
	}
	
	/**
	 * 初始化处理类
	 * @param socket
	 */
	public Processor(Socket socket){
		this.socket=socket;
		try {
			this.in=socket.getInputStream();
			this.out=new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void run(){
		String filename=parseIn(in);
		sendFile(filename);
	}
	
	public String parseIn(InputStream in){
		String filename=null;
		
		try {
			BufferedReader buff=new BufferedReader(new InputStreamReader(in));
			String httpMessage=buff.readLine();
			if(httpMessage==null)
				return null;
			String [] content=httpMessage.split(" ");
			if(content.length!=3){
				sendErrorMessage(400,"Client query error");
				return null;
			}
			filename=content[1];
		} catch (IOException e) {
			e.printStackTrace();
		}
		return filename;
	}
	
	public void sendErrorMessage(int errorCode,String errorMessage){
		out.println("HTTP/1.0 "+errorCode+" "+errorMessage);
		out.println("content-type:text/html");
		out.println();
		out.println("<html>");
		out.println("<title>ERROR MESSAGE</title>");
		out.println("<body>");
		out.println("<h1>errorcode:"+errorCode+",errorMessage"+errorMessage);
		out.println("</body>");
		out.println("</html>");
		out.flush();
		out.close();
	}
	
	public void sendFile(String filename){
		File file=new File(Processor.WEB_ROOT+filename);
		if(!file.exists()){
			sendErrorMessage(404,"File Not Found!");
			return;
		}
		byte [] b=new byte[(int)file.length()];
		try {
			InputStream in= new FileInputStream(file);
			in.read(b);
			out.println("HTTP/1.0 200 queryfile");
			out.println("content-length:"+b.length);
			out.println();
			out.write(b);
			out.flush();
			out.close();
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}
}
